package com.zjm.upload;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @author ZJM
 * @date 2024/4/23 21:16
 * 文件下载
 */
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取要下载的文件名
        String downloadFileName = "test.txt";
        // 2.读取要下载的文件内容
        ServletContext servletContext = getServletContext();
        // 4.设置响应头
        String mimeType = servletContext.getMimeType("/file/" + downloadFileName);
        System.out.println(mimeType);
        resp.setContentType(mimeType);
        // 5.告诉客户端用于下载使用
        //attachment附件
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("测试.txt", "UTF-8"));
        InputStream inputStream = servletContext.getResourceAsStream("/file/" + downloadFileName);
        //获取响应输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        //流复制
        IOUtils.copy(inputStream, outputStream);
        // 3.把下载的文件内容回传给客户端
    }
}
